# -*- coding: utf-8 -*-
# author yzs
# date 2019-02-23
#
# 广度优先遍历
# Description
# 按照给定的起始顶点广度优先遍历图，每一次通过字母顺序选择顶点查找下一层邻接点，打印遍历顺序
# Input
# 输入第一行是用例个数，后面每个用例使用多行表示，用例的第一行是图中节点的个数n和起始点，用空格隔开，
# 后面n+1行为图的邻接矩阵，其中第一行为节点名称。值之间使用空格隔开
# Output
# 输出深度优先遍历中遇到的最大深度
# Sample Input 1
# 1
# 4 a
# a b c d
# a 0 1 1 0
# b 1 0 1 0
# c 1 1 0 1
# d 0 0 1 0
# Sample Output 1
# a b c d


class Graph(object):
    def __init__(self, maps):
        self.maps = maps
        self.node_num = self.get_node_num()
        self.edge_num = self.get_edge_num()

    def get_node_num(self):
        return len(self.maps)

    def get_edge_num(self):
        count = 0
        for i in range(self.node_num):
            for j in range(i):
                if self.maps[i][j] > 0:
                    count += 1
        return count

    def breath_first_search(self, start):
        queue = []
        visited = [False] * self.node_num
        res = []

        def bfs():
            while len(queue) > 0:
                i = queue.pop(0)
                for j in range(self.node_num):
                    if self.maps[i][j] > 0 and visited[j] is False:
                        res.append(j)
                        visited[j] = True
                        queue.append(j)

        if self.node_num <= 0:
            return res
        else:
            queue.append(start)  # index, value
            visited[start] = True
            res.append(start)
            bfs()

        for i in range(self.node_num):
            if visited[i] is False:
                res.append(i)
                visited[i] = True
                queue.append(i)
                bfs()

        return res


t = int(input().strip())
for i in range(t):
    n, start = input().strip().split()
    points = list(map(str, input().strip().split()))
    maps = []
    for i in range(int(n)):
        maps.append(list(map(int, input().strip().split()[1:])))
    graph = Graph(maps)
    start_index = points.index(start)
    res = graph.breath_first_search(start_index)
    print(' '.join(str(points[i]) for i in res))

